<?php

namespace App\Service;

use App\Models\CourseArrangeModel;
use App\Models\CoursePriceModel;
use App\Models\EmployeesModel;
use App\Repositories\CourseArrangeRepository;

use App\Repositories\CoursePriceRepository;
use App\Repositories\CourseStudentRepository;
use App\Repositories\EmployeesRepository;
use Illuminate\Support\Arr;
use App\Service\CommonService;
use Illuminate\Support\Facades\DB;

class CourseArrangeService extends BaseService {
    protected $courseArrangeRepository;
    protected $employeesRepository;
    protected $courseStudentRepository;
    protected $coursePriceRepository;

    public function __construct(
        CourseArrangeRepository $courseArrangeRepository,
        EmployeesRepository $employeesRepository,
        CourseStudentRepository $courseStudentRepository,
        CoursePriceRepository $coursePriceRepository
    ){
        $this->courseArrangeRepository = $courseArrangeRepository;
        $this->employeesRepository = $employeesRepository;
        $this->courseStudentRepository = $courseStudentRepository;
        $this->coursePriceRepository = $coursePriceRepository;
    }

    /**
     * 课程列表
     * @param $filterParams
     * @return array
     */
    public function list($filterParams) {
        $q = !empty($filterParams['course_name']) ? ['course_name' => $filterParams['course_name']] : [];
        $q = !empty($filterParams['school_id']) ? array_merge(['school_id' => $filterParams['school_id']], $q) : $q;
        $q = !empty($filterParams['user_name']) ? array_merge(['username' => $filterParams['username']], $q) : $q;
        $filterParams['where'] = $q;
        $where = !empty($filterParams['status']) ? ['status' => $filterParams['status']] : [];
        $courseArrageInfoResource = $this->courseArrangeRepository->list($filterParams, ['school', 'course', 'teacher'], $where);
        $courseArrageInfoCollection = new Collection($courseArrageInfoResource, $this->listTransformer);
        $courseArrageInfoCollection->setPaginator(new IlluminatePaginatorAdapter($courseArrageInfoResource));
        return responseData($this->fractal, $courseArrageInfoCollection);
    }

    /**
     * 批量排课
     * @param $data
     * @return array
     */
    public function store(array $params) {
//        $userInfo = $this->employeesRepository->showOrFail(1)->toArray();
//        session(['employeesInfo'=>$userInfo]);
//        return;
        $userInfo = session('employeesInfo');
        //判断排课是否是当前员工所在校区
        if ($userInfo['school_id'] != $params['school_id']){
            throw new \Exception(CommonService::getExceptionInfo(1006),1006);
        }
        //判断课程级别是否存在
        if (empty($this->getCoursePrice($params['course_id'],$params['level_id']))){
            throw new \Exception(CommonService::getExceptionInfo(1007),1007);
        }
        DB::transaction(function () use ($params,$userInfo,&$result){
            foreach ($params['time_day'] as $key => $timeInfo){
                $beginTime = $timeInfo.' '.$params['begin_clock'];
                $endTime = $timeInfo.' '.$params['end_clock'];
                $courseInfo = [];
                $courseInfo['begin_time'] = $beginTime;
                $courseInfo['end_time'] = $endTime;
                $courseInfo['arrange_user'] = $userInfo['id'];
                $courseInfo['course_serial_number'] = buildOrderNo();
                $courseInfo = array_merge($courseInfo,Arr::except($params,['time_day','begin_clock','end_clock','student_id']));
                $checkArrangeCourseConflict = $this->checkArrangeCourseConflict($beginTime, $endTime, $params['teacher_id']);
                if ($checkArrangeCourseConflict) {
                    throw new \Exception(CommonService::getExceptionInfo(1005),1005);
                }
                $courseArrangeId = $this->courseArrangeRepository->getStoreId($courseInfo);
                $courseStudentData = $this->handleRelationData('student_id', $params['student_id'], ['course_arrange_id' => $courseArrangeId]);
                $result = $this->courseStudentRepository->batchInsert($courseStudentData);
            }
        });
        return $result;
    }

    /**
     * 获取课程信息
     * @param $courseId
     * @param $levelId
     * @return array
     */
    private function getCoursePrice($courseId,$levelId){
        $coursePriceData = $this->coursePriceRepository->showByWhere(['course_id','level_id']);
        return !empty($coursePriceData) ? $coursePriceData->toArray() : [];
    }

    /**
     * 课程安排修改
     * @param $id
     * @param $data
     * @return mixed
     */
    public function update($id, $data) {
        \DB::transantion(function () use($id, $data, &$courseArrangeInfo) {
            if (!empty($data['student_id'])) {
                $courseStudentData = $this->handleRelationData('user_id', explode(',', $data['student_id']), ['course_arrange_id' => $id]);
                $this->courseStudentRepository->batchInsert($courseStudentData);
            }
            $courseArrangeInfo = $this->courseArrangeRepository->update($id, Arr::except($data, ['student_id']));
        });
        return $courseArrangeInfo;
    }

    /**
     * 排课取消
     * @param $courseArrangeId
     * @return mixed
     */
    public function delete($courseArrangeId) {
        \DB::transantion(function () use($courseArrangeId, &$courseArrangeInfo) {
            $this->courseStudentRepository->deleteByWhereIn('course_arrange_id', explode(',', $courseArrangeId));
            $courseArrangeInfo = $this->courseArrangeRepository->delete(explode(',', $courseArrangeId));
        });
        return $courseArrangeInfo;
    }

    /**
     * 检测排课是否存在冲突
     * @param $beginTime
     * @param $endTime
     * @param $teacherId
     * @return mixed
     */
    private function checkArrangeCourseConflict($beginTime, $endTime, $teacherId) {
        $whereArr= [
            'teacher_id'=>$teacherId,
            'begin_time'=>$beginTime,
            'end_time'=>$endTime,
        ];
        return $this->courseArrangeRepository->showByWhere($whereArr);
    }
}
